package com.ecommerce.onion.application;

import com.ecommerce.onion.application.request.AddProductRequest;
import com.ecommerce.onion.application.request.CreateOrderRequest;
import com.ecommerce.onion.application.response.OrderResponse;
import com.ecommerce.onion.domain.Product;
import com.ecommerce.onion.domain.service.OrderService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
/**
 * @packageName: application（应用包）
 * @className: OrderController(订单控制器)
 * @description: 围绕此订单领域展开业务
 * @author: luds
 * @version: v1.0
 * @date: 2021-04/03
 */
@RestController
@RequestMapping("/orders")
public class OrderController {
	/**
	 * 订单服务
	 */
	private final OrderService orderService;

	/**
	 * 由订单服务自动装配订单控制器
	 * @param orderService
	 */
	@Autowired
	public OrderController(OrderService orderService) {
		this.orderService = orderService;
	}

	/**
	 * 由创建订单请求创建订单，并返回创建订单响应
	 * @param createOrderRequest 创建订单请求
	 * @return 返回创建订单响应
	 */
	@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	OrderResponse createOrder(@RequestBody final CreateOrderRequest createOrderRequest) {

		Product product = createOrderRequest.product();

		final UUID id = orderService.createOrder(product);

		return new OrderResponse(id,product.getId());
	}

	/**
	 * 此订单ID上追加产品请求
	 * @param id 订单ID
	 * @param addProductRequest 追加产品请求
	 */
	@PostMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE)
	OrderResponse addProduct(@PathVariable final UUID id, @RequestBody final AddProductRequest addProductRequest) {
		Product product = addProductRequest.product();

		orderService.addProduct(id, product);

		return new OrderResponse(id,product.getId());
	}

	/**
	 * 从此订单ID上删除产品ID
	 * @param id 订单ID
	 * @param productId 产品ID
	 */
	@DeleteMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE)
	void deleteProduct(@PathVariable final UUID id, @RequestParam final UUID productId) {
		orderService.deleteProduct(id, productId);
	}

	/**
	 * 完成订单
	 * @param id 订单ID
	 */
	@PostMapping("/{id}/complete")
	void completeOrder(@PathVariable final UUID id) {
		orderService.completeOrder(id);
	}
}
